package com.hn.zhijian.web.controller;


import com.hn.zhijian.base.common.exception.ApplicationException;
import com.hn.zhijian.base.common.StatusCode;
import com.hn.zhijian.base.log.annotation.Log;
import com.hn.zhijian.base.redis.RedisService;
import com.hn.zhijian.system.entity.SysUser;
import com.hn.zhijian.system.exception.SystemError;
import com.hn.zhijian.system.model.response.UserResponse;
import com.hn.zhijian.system.service.IUserService;
import com.hn.zhijian.utils.BeanCopier;
import com.hn.zhijian.utils.Md5Utils;
import com.hn.zhijian.utils.Utils;
import com.hn.zhijian.web.config.jwt.JwtExecute;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * Function:登录控制器. <br/>
 *
 * @author 11
 */
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/account")
@Slf4j
public class AccountController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtExecute jwtExecute;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     *
     * @return
     */
    @CrossOrigin
    @GetMapping(value = "/login")
    @Log(module = "用户授权模块", description = "用户登录")
    public UserResponse login(@RequestParam(value = "userName") String username, @RequestParam(value = "password") String password) {

        SysUser user = userService.getUser(username);

        if (Utils.isEmpty(user)) {
            throw new ApplicationException(StatusCode.INVALID_USER);
        }

        //记录的密码
        String dbPassword = Md5Utils.getStringMD5(password);

        if (!dbPassword.trim().equals(user.getPassword())) {
            throw new ApplicationException(StatusCode.INVALID_USER);
        }

        UserResponse userResponse = BeanCopier.copyJSONObject(user,UserResponse.class);

        userResponse.setToken(jwtExecute.sign(user.getUsername()));
        //token存在到缓存中
        redisService.set(userResponse.getToken(), user);

        return userResponse;
    }

    /**
     * 登出
     *
     * @return
     */
    @GetMapping("/logout")
    @CrossOrigin
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return StatusCode.OK.getMessage();
    }
}
